<?php

namespace app\models\user;

use app\models\constant\Status;
use Yii;
use app\models\City;

/**
 * This is the model class for table "user_address".
 *
 * @property int $id
 * @property int $user_id
 * @property string $create_time
 * @property string $update_time
 * @property int $table_id 这个是关联到地址表的ID
 * @property int $region_id
 * @property int $province_id
 * @property int $city_id
 * @property int $area_id
 * @property string $address 详情地址
 * @property int $is_default 是否为默认地址, 1是, 0不是
 * @property string $mobile 收货电话
 * @property string $nickname 收货姓名
 * @property int $status 状态 
 */
class UserAddress extends \yii\db\ActiveRecord
{
    use Status;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'user_address';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['user_id', 'table_id', 'region_id', 'province_id', 'city_id', 'area_id', 'is_default', 'status'], 'integer'],
            [['create_time', 'update_time'], 'safe'],
            [['address'], 'string', 'max' => 200],
            [['mobile'], 'string', 'max' => 50],

            [['nickname'], 'safe']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'table_id' => 'Table ID',
            'region_id' => 'Region ID',
            'province_id' => 'Province ID',
            'city_id' => 'City ID',
            'area_id' => 'Area ID',
            'address' => 'Address',
            'is_default' => 'Is Default',
            'mobile' => 'Mobile',
            'nickname' => 'Nickname',
            'status' => 'Status',
        ];
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    public function getCity()
    {
        return $this->hasOne(City::class, ['id' => 'table_id']);
    }
}
